<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择班级" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptOptions" placeholder="请选择归属部门"
                    style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="学年" prop="semesterYear">
        <el-date-picker
          v-model="queryParams.semesterYear"
          type="year"
          value-format="yyyy"
          placeholder="选择学年">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="学期" prop="semester">
        <el-select v-model="queryParams.semester" placeholder="请选择" clearable style="width: 240px">
          <el-option
            v-for="item in dict.type.semester"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.payment_project_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="缴费类型" prop="status">
        <el-select v-model="queryParams.other" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.pay_order_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校" prop="school" v-if="false">
        <el-input
          v-model="queryParams.school"
          placeholder="请输入学校"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学院" prop="college" v-if="false">
        <el-input
          v-model="queryParams.college"
          placeholder="请输入学院"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="专业" prop="major" v-if="false">
        <el-input
          v-model="queryParams.major"
          placeholder="请输入专业"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级" prop="clazz" v-if="false">
        <el-input
          v-model="queryParams.clazz"
          placeholder="请输入班级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-input
          v-model="queryParams.grade"
          placeholder="请输入年级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="签发日期" prop="issuanceDate" v-if="false">
        <el-date-picker clearable
                        v-model="queryParams.issuanceDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择签发日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 新增 -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['uniquefees:bookList:add']"
        >新增
        </el-button>
      </el-col>
      <!-- 修改 -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['uniquefees:bookList:edit']"
        >修改
        </el-button>
      </el-col>
      <!-- 删除 -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['uniquefees:bookList:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      导出-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['uniquefees:bookList:export']"
        >导出
        </el-button>
      </el-col>
      <el-dropdown :hide-on-click="false" class="top-right-btn">
          <span class="el-dropdown-link">
            <el-button size="mini" icon="el-icon-setting" circle></el-button>
          </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="field in columns" :key="field.key">
            <el-checkbox :value="field.visible" @change="downChange(field.key)">{{ field.label }}</el-checkbox>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookListList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="清单" align="center" prop="booklistPic" show-overflow-tooltip v-if="columns[15].visible">
        <template slot-scope="scope">
          <image-preview :src="scope.row.booklistPic" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="主键" align="center" prop="id" v-if="columns[16].visible"/>
      <el-table-column label="学期年" align="center" prop="semesterYear" v-if="columns[0].visible"/>
      <el-table-column label="学期" align="center" prop="semester" v-if="columns[1].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.semester" :value="scope.row.semester"/>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="name" width="180px" v-if="columns[2].visible"/>
      <el-table-column label="总价" align="center" prop="pricesum" v-if="columns[3].visible">
        <template slot-scope="scope">
          {{ scope.row.pricesum / 100 }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" v-if="columns[4].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_project_state" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="学校" align="center" prop="school" width="180px" v-if="columns[5].visible"/>
      <el-table-column label="学院" align="center" prop="college" width="180px" v-if="columns[6].visible"/>
      <el-table-column label="专业" align="center" prop="major" width="180px" v-if="columns[7].visible"/>
      <el-table-column label="班级" align="center" prop="clazz" v-if="columns[8].visible"/>
      <el-table-column label="年级" align="center" prop="grade" v-if="columns[9].visible"/>
      <el-table-column label="缴费类型" align="center" prop="other" v-if="columns[10].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_order_type" :value="scope.row.other"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" v-if="columns[11].visible"/>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[12].visible"/>
      <el-table-column label="更新者" align="center" prop="updateBy" v-if="columns[13].visible"/>
      <el-table-column label="更新者" align="center" prop="updateTime" v-if="columns[14].visible"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['uniquefees:bookList:edit']"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['uniquefees:bookList:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleStatusChange(scope.row, 1)"
            icon="el-icon-switch-button"
            v-hasPermi="['uniquefees:bookList:edit']"
            v-if="scope.row.status==='2'">
            暂停
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-magic-stick"
            v-hasPermi="['uniquefees:bookList:edit']"
            @click="handleStatusChange(scope.row, 2)"
            v-if="scope.row.status==='1'">
            激活
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-if="false"
                       v-hasPermi="['uniquefees:bookList:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="handleCourseBookList"
                icon="el-icon-reading"
                v-hasPermi="['uniquefees:bookList:edit']">
                关联教材
              </el-dropdown-item>
              <el-dropdown-item
                command="handleStudentBookList"
                icon="el-icon-s-order"
                v-hasPermi="['uniquefees:bookList:edit']">
                订购名单
              </el-dropdown-item>
              <el-dropdown-item
                command="activate"
                icon="el-icon-magic-stick"
                v-hasPermi="['uniquefees:bookList:edit']"
                v-if="scope.row.status==='1'">
                激活
              </el-dropdown-item>
              <el-dropdown-item
                command="suspend"
                icon="el-icon-switch-button"
                v-hasPermi="['uniquefees:bookList:edit']"
                v-if="scope.row.status==='2'">
                暂停
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数目清单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="170px">
        <el-form-item label="类型" prop="other">
          <el-radio-group v-model="form.other">
            <el-radio-button
              v-for="dict in dict.type.pay_order_type"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学期" prop="semesterYear" style="margin-right: 10px;">
          <el-col :span="8">
            <el-date-picker style="width: 100px;" v-model="form.semesterYear" type="year" value-format="yyyy"
                            placeholder="选择学年"/>
          </el-col>
          <el-col class="line" :span="8"></el-col>
          <el-col :span="12">
            <el-radio-group v-model="form.semester">
              <el-radio label="C">春季</el-radio>
              <el-radio label="Q">秋季</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="班级" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择班级"/>
          <!--          <span>{{ clazzName }}</span>-->
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入年级"/>
        </el-form-item>
        <el-form-item label="标题" prop="name">
          <el-input v-model="form.name" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="单价 (元)" prop="pricesum" v-if="form.other==='SPECIAL'">
          <el-input v-model="priceInYuan" type="text" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="班主任" prop="headteacher">
          <el-input v-model="form.headteacher" placeholder="请输入班主任"/>
        </el-form-item>
        <el-form-item label="班主任电话" prop="headteacherTel">
          <el-input v-model="form.headteacherTel" placeholder="请输入班主任电话"/>
        </el-form-item>
        <el-form-item label="书目清单图片" prop="booklistPic" v-if="form.other==='SPECIAL'">
          <image-upload :limit="1" v-model="form.booklistPic"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 订购名单-->
    <el-drawer
      size="70%"
      title="个性化缴费名单"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose">
      <list-stu-book v-model="ids"></list-stu-book>
    </el-drawer>

    <el-drawer
      size="70%"
      title="专项缴费名单"
      :visible.sync="drawer2"
      direction="rtl"
      :before-close="handleClose">
      <stu_-list v-model="form"></stu_-list>
    </el-drawer>

    <!--  关联教材   -->
    <el-drawer
      size="70%"
      title="关联教材"
      :visible.sync="drawerDetail"
      direction="rtl"
      :before-close="handleClose">
      <book-detail v-model="ids"></book-detail>
    </el-drawer>

  </div>
</template>

<script>
import {
  addBookList,
  changeStatus,
  delBookList,
  getBookList,
  listBookList,
  updateBookList
} from "@/api/uniquefees/bookList";
import BookDetail from "@/views/uniquefees/bookList/bookDetail/index.vue";
import ListStuBook from "@/views/uniquefees/bookList/stuBook/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {deptSchoolTreeSelect} from "@/api/campus/Org";
import Stu_List from "@/views/uniquefees/bookList/stuList/index.vue";

export default {
  name: "BookList",
  components: {Stu_List, Treeselect, ListStuBook, BookDetail},
  dicts: ['semester', 'sys_normal_disable', 'pay_order_type', 'payment_project_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 部门树选项
      deptOptions: [],
      // 数目清单表格数据
      bookListList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 订购名单
      drawer: false,
      drawer2: false,
      // 教材清单
      drawerDetail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        semesterYear: null,
        semester: null,
        deptId: null,
        status: null,
        sysOrgCode: null,
        code: null,
        name: null,
        school: null,
        college: null,
        major: null,
        clazz: null,
        grade: null,
        collegeId: null,
        schoolId: null,
        majorId: null,
        clazzId: null,
        headteacher: null,
        headteacherTel: null,
        headstudent: null,
        headstudentTel: null,
        issuanceDate: null,
        other: null,
        schoolYear: null,
        pricesum: null,
        booklistPic: null,
        bookListDetail: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        semesterYear: [
          {required: true, message: "学期年不能为空", trigger: "blur"}
        ],
        deptId: [
          {required: true, message: "班级不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "标题不能为空", trigger: "blur"}
        ],
        pricesum: [
          {required: true, message: "价格不能为空", trigger: "blur"}
        ],
        priceInYuan: [
          {required: true, message: '请输入价格', trigger: 'blur'},
          {
            pattern: /^\d{0,8}(\.\d{0,2})?$/,
            message: '请输入有效的价格（最多8位整数和2位小数）',
            trigger: ['blur', 'change']
          }
        ],
      },
      // 列信息
      columns: [
        {key: 0, label: `学期年`, prop: 'semesterYear', visible: true},
        {key: 1, label: `学期`, prop: 'semester', visible: true},
        {key: 2, label: `标题`, prop: 'name', visible: true},
        {key: 3, label: `总价`, prop: 'pricesum', visible: false},
        {key: 4, label: `状态`, prop: 'status', visible: true},
        {key: 5, label: `学校`, prop: 'school', visible: false},
        {key: 6, label: `学院`, prop: 'college', visible: false},
        {key: 7, label: `专业`, prop: 'major', visible: false},
        {key: 8, label: `班级`, prop: 'clazz', visible: false},
        {key: 9, label: `年级`, prop: 'grade', visible: false},
        {key: 10, label: `缴费类型`, prop: 'other', visible: true},
        {key: 11, label: `创建人`, prop: 'createBy', visible: false},
        {key: 12, label: `创建时间`, prop: 'createTime', visible: false},
        {key: 13, label: `更新者`, prop: 'updateBy', visible: false},
        {key: 14, label: `更新时间`, prop: 'updateTime', visible: false},
        {key: 15, label: `清单`, prop: 'booklistPic', visible: false},
        {key: 16, label: `主键`, prop: 'id', visible: false},
      ],
    };
  },
  created() {
    this.getDeptTree();
    this.getList();
  },
  computed: {
    // 以元为单位的价格，用于表单展示和输入
    priceInYuan: {
      get() {
        return (this.form.pricesum / 100).toFixed(2);
      },
      set(value) {
        this.form.pricesum = Math.round(value * 100);
      }
    }
  },
  methods: {
    /** 查询数目清单列表 */
    getList() {
      this.loading = true;
      listBookList(this.queryParams).then(response => {
        this.bookListList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptSchoolTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        semesterYear: null,
        semester: null,
        deptId: null,
        remark: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        sysOrgCode: null,
        code: null,
        name: null,
        school: null,
        college: null,
        major: null,
        clazz: null,
        grade: null,
        collegeId: null,
        schoolId: null,
        majorId: null,
        clazzId: null,
        headteacher: null,
        headteacherTel: null,
        headstudent: null,
        headstudentTel: null,
        issuanceDate: null,
        other: "SPECIAL",
        schoolYear: null,
        pricesum: null,
        booklistPic: null,
        bookListDetail: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数目清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      if (row.other === 'UNIQUE') {
        this.$router.push("/payment/info/project/" + id);
      } else {
        this.$router.push("/payment/info/special/" + id);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBookList(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBookList(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数目清单编号为"' + ids + '"的数据项？').then(function () {
        return delBookList(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /**
     * 缴费项目状态切换
     */
    handleStatusChange(row, status) {
      const text = status === 2 ? "激活" : "暂停";
      const data = {id: row.id, status: status}
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"缴费项目？').then(() => {
        return changeStatus(data);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      }).catch(_ => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('uniquefees/bookList/export', {
        ...this.queryParams
      }, `bookList_${new Date().getTime()}.xlsx`)
    },
    /**
     *  名单详情页
     */
    handleStudentBookList(row) {
      this.form = {}
      this.reset();
      this.ids = [row.id]
      getBookList(this.ids).then(response => {
        if (response.data.other === 'SPECIAL') {
          this.form = response.data;
          this.drawer2 = true;
        }
        if (response.data.other === 'UNIQUE') {
          this.drawer = true;
        }
      });

    },
    /**
     * 教材详情页
     */
    handleCourseBookList(row) {
      this.ids = [row.id]
      if (row.other === 'UNIQUE') {
        this.drawerDetail = true;
      } else {
        this.$modal.msgWarning("非个性化缴费项目无需关联！");
      }
      // if (row.other==='SPECIAL')

    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleCourseBookList":
          this.handleCourseBookList(row);
          break;
        case "handleStudentBookList":
          this.handleStudentBookList(row);
          break;
        case "activate":
          this.handleStatusChange(row, 2);
          break;
        case "suspend":
          this.handleStatusChange(row, 1);
          break;
        default:
          break;
      }
    },
    downChange(val) {
      const column = this.columns.find(col => col.key === val);
      if (column) {
        column.visible = !column.visible;
      }
    }
  }
};
</script>
<style>
/* 在你的样式文件中添加以下样式 */
.el-table th,
.el-table td {
  white-space: nowrap; /* 禁止换行 */
}
</style>
